var http = "https://goead2.ysxdgy.com/Wechatapps/";
var imgUrl = "https://goead2.ysxdgy.com/Public/Wechatapps/images/";
var QQMapKey = "XBTBZ-S6HWX-JGU47-Z3N5W-6CWSZ-DFFL2";
// 网络错误提示
function cwtx() {
    showModal('请求中断!', false, () => {
        wx.reLaunch({
            url: '/pages/login/login'
        })
    })
}
// 600错误提示
function cwtx1(res) {
    wx.showModal({
        title: '提示',
        content: res.data.info,
        showCancel: false,
        confirmText: "重新登陆",
        complete() {
            wx.reLaunch({
                url: '/pages/login/login'
            })
        }
    })
}

function showModal(cont, flag, fn) {
    wx.showModal({
        title: '提示',
        content: cont,
        showCancel: flag,
        success(res) {
            if (res.confirm) {

            } else if (res.cancel) {}
        },
        complete() {
            fn()
            wx.hideLoading()
        }
    })
};

function showModal1(cont, flag, fn, fn1) {
    wx.showModal({
        title: '温馨提示',
        content: cont,
        showCancel: flag,
        success(res) {
            if (res.confirm) {
                fn()
            } else if (res.cancel) {
                fn1()
            }
        },
        complete() {
            wx.hideLoading()
        }
    })
};

function showModal2(cont, flag, fn, fn1) {
    wx.showModal({
        title: '温馨提示',
        content: cont,
        showCancel: flag,
        success(res) {
            if (res.confirm) {
                fn()
            } else if (res.cancel) {
                fn1()
            }
        },
    })
};

// 带头部请求
function _post(url, data, success, fail) {
    data.unionid = wx.getStorageSync('thisCode');
    wx.request({
        url: http + url,
        header: {
            'content-type': 'application/x-www-form-urlencoded',
        },
        method: 'POST',
        data: data,
        success(res) {
            wx.hideLoading();
            wx.stopPullDownRefresh();
            console.log(res.data)
            if (!res.data.status && res.data.status != 0) {
                cwtx()
                return;
            } else if (res.data.status == 600) {
                cwtx1(res)
                return
            } else if (res.data.status == 6) {
                showModal('请先进行账号绑定!', false, () => {
                    wx.reLaunch({
                        url: '/pages/login/login'
                    })
                })
                return
            } else if (res.data.status == 0) {
                showModal(res.data.info, false, () => {})
                return
            }

            success(res);
        },
        fail(res) {
            fail(res);
        }
    });
}
// 带头部请求
function _post2(url, data, success, fail) {
    wx.request({
        url: http + '/WeChatApps/' + url,
        header: {
            'content-type': 'application/x-www-form-urlencoded',
        },
        method: 'POST',
        data: data,
        success(res) {
            wx.stopPullDownRefresh();
            console.log(res.data)
            if (!res.data.status && res.data.status != 0) {
                cwtx()
                return;
            } else if (res.data.status == 600) {
                cwtx1(res)
                return
            }
            success(res);
        },
        fail(res) {
            fail(res);
        }
    });
}

function loginFn(fn) {
    wx.login({
        success(res) {
            var code = res.code;
            wx.getUserInfo({
                success(res) {
                    var encryptedData = res.encryptedData;
                    var iv = res.iv;
                    _post('Login/login', {
                        code: code,
                        encryptedData: encryptedData,
                        iv: iv,
                    }, res => {
                        let unionid = res.data.info.unionid;
                        console.log(unionid)
                        wx.setStorageSync('thisCode', unionid);
                        fn(unionid, res);
                    }, res => {})
                },
                fail(res) {
                    wx.reLaunch({
                        url: '/pages/wsq/wsq'
                    })
                },
            })
        }
    })
}

function baseLogin(fn) {
    wx.login({
        success(res) {
            var code = res.code;
            wx.getUserInfo({
                success(res) {
                    var encryptedData = res.encryptedData;
                    var iv = res.iv;
                    fn(encryptedData, code, iv)
                },
                fail(res) {
                    wx.reLaunch({
                        url: '/pages/wsq/wsq'
                    })
                },
            })
        }
    })
}
// 获取data-index 属性
function dataIndex(e) {
    var a = e.currentTarget.dataset.index;
    var b = e.currentTarget.dataset.id;
    var d = e.currentTarget.dataset.type;
    var e = e.currentTarget.dataset.name;
    var c = [a, b, d, e];
    return c
}
// 图片去空格输出
function imgSup(arr) {
    var cc = []
    for (let k in arr) {
        let aa = arr[k].replace(/[\r\n]/g, "");
        let bb = aa.replace("https://pintuanqu.oss-cn-hangzhou.aliyuncs.com", "");
        cc.push(bb);
    }
    return cc
}

function upImgAllSuccss(res, formData, success) {
    var upImgBoxArr = res.tempFilePaths;
    var imgarr = [];
    for (var j in upImgBoxArr) {
        if (res.tempFiles[j].size > 2097152) {
            http.showModal('有图片已超过2MB,您可以选择压缩图片以后重新上传', false, () => {})
            continue;
        }
        var turnsImgUrl = wx.uploadFile({
            url: http + '/WeChatApps/StoreGoods/upload_goods_image',
            filePath: upImgBoxArr[j],
            name: 'fileData', //这里根据自己的实际情况改
            herder: { 'content-type': 'multipart/form-data;' },
            formData: formData,
            success: (resp) => {
                success(resp)
            },
        });
    }
}

function upImgAllSuccssAll(res, formData, success, url) {
    var upImgBoxArr = res.tempFilePaths;
    var imgarr = [];
    for (var j in upImgBoxArr) {
        if (res.tempFiles[j].size > 2097152) {
            http.showModal('有图片已超过2MB,您可以选择压缩图片以后重新上传', false, () => {})
            continue;
        }
        var turnsImgUrl = wx.uploadFile({
            url: http + '/WeChatApps/' + url,
            filePath: upImgBoxArr[j],
            name: 'fileData', //这里根据自己的实际情况改
            herder: { 'content-type': 'multipart/form-data;' },
            formData: formData,
            success: (resp) => {
                success(resp)
            },
        });
    }
}
// 图片上传的封装
function upImgAll(imgArr, success, num) {
    var num = num || 9;
    if (imgArr.length >= num) {
        showModal('最多上传' + num + '张图片，请删除图片后继续上传', false, () => {})
        return;
    }
    wx.chooseImage({
        count: num - Number(imgArr.length), // 默认9
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        success(res) {
            success(res)
        },
    });
}
// 基础图片上传封装
function oneImg(success) {
    wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
            success(res)
        },
    });
}

// 扫描二维码进入对应界面
function ewmBtn() {
    wx.scanCode({
        success: (res) => {
            var path = res.path;
            console.log(path)
            if (!path) {
                showModal('此二维码不属于内部二维码,请扫描本程序的二维码', false, () => {})
                return;
            }
            var path1 = path.substring(22);
            console.log(path1);
            var path2 = path1.substring(0, 5);
            var code_type;
            // 判断是否是b类接口
            console.log(path2)
            if (path2 == "scene") {
                var scene = path1.substring(6);
                var sceneArr = scene.split("-");
                for (let i = 0; i < sceneArr.length; i += 2) {
                    if (sceneArr[i] == "code_type") {
                        code_type = sceneArr[i + 1]
                    };
                }
                console.log(code_type);
                if (code_type == 4) {
                    wx.reLaunch({
                        url: '../../' + path
                    })
                }
            } else if (path2 == "code_") {
                var options = path1;
                // console.log(options)
                wx.reLaunch({
                    url: '../../' + path
                })
            } else if (path2 == "store") {
                wx.reLaunch({
                    url: '../../' + path
                })
            } else {
                wx.reLaunch({
                    url: '../../' + path
                })
            }
        }
    })
}
// 检测移动状态的封装
function moveFn(e, touchDotY, touchDot, time, fn, fn1, flag) {
    let touchMove = e.touches[0].pageX;
    let touchMoveY = e.touches[0].pageY;
    // 检测是否点击以后上下滑动//清空时间数据
    if (Number(touchDotY) - Number(touchMoveY) > 15 || Number(touchDotY) - Number(touchMoveY) < -15) {
        time = 0;
        return;
    }
    //向左滑动
    if (touchMove - touchDot <= -60 && !flag && time >= 2) {
        fn()
    }
    //向右滑动
    if (touchMove - touchDot >= 60 && !flag && time >= 2) {
        fn1()
    }
}
// 清空数组判断对象
function forC(arr) {
    for (let i in arr) {
        arr[i] = ''
    }
    return arr
}
// 获取input框里面所有的数据
function inputArr(arr, e) {
    var index = dataIndex(e)[0];
    var a = arr;
    var b = e.detail.value;
    a[index] = b;
    return a
}
// 正则匹配方法的封装
function rexFn(str) {
    // 手机的正则匹配
    var rex1 = /^1\d{10}$/;
    // 身份证正则匹配
    var rex2 = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    // 汉字匹配
    var rex3 = /^[\u4e00-\u9fa5]+$/;
    var falgArr = []
    if (rex1.test(str)) {
        falgArr[0] = 1
    } else if (rex2.test(str)) {
        falgArr[1] = 1
    } else if (rex3.test(str)) {
        falgArr[2] = 1
    }
    return falgArr;
}
// 如果为空返回空
function inputUn(arr, num) {
    for (var i = 0; i < num; i++) {
        !arr[i] ? arr[i] = '' : arr[i] = arr[i];
    }
    return arr
}
// 支付的封装
function payFn(data, fn, fn2) {
    var payT = data.jsApiParameters;
    wx.requestPayment({
        'timeStamp': payT.timeStamp,
        'nonceStr': payT.nonceStr,
        'package': payT.package,
        'signType': 'MD5',
        'paySign': payT.paySign,
        'success' (res) {
            fn(res)
        },
        'fail' (res) {
            fn2(res)
        }
    })
}
// 数字隐私处理
const passStrat = num => {
    var newTel = []
    for (let i = 0; i < num.length; i++) {
        let aa = num.substring(i, i + 1);
        if (i >= 3 && i <= 7) {
            aa = '*'
        }
        newTel.push(aa);
    }
    var newTelS = newTel.join("");
    return newTelS
}
// 版本比较

function compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    var len = Math.max(v1.length, v2.length)

    while (v1.length < len) {
        v1.push('0')
    }
    while (v2.length < len) {
        v2.push('0')
    }

    for (var i = 0; i < len; i++) {
        var num1 = parseInt(v1[i])
        var num2 = parseInt(v2[i])

        if (num1 > num2) {
            return 1
        } else if (num1 < num2) {
            return -1
        }
    }

    return 0
}
function canClick(num, arr) {
   let aa = 0
   for (let i = 0; i < num; i++) {
      if (arr[i]) {
         aa++
      }
   }
   return aa == num ? true : false
}
// 跳转小程序
function ToMiniProgram(appId, path, data) {
   wx.navigateToMiniProgram({
      appId: appId,
      path: path,
      extraData: data,
      envVersion: 'release',
      success: function (res) {
         console.log(res)
      }
   })
}
module.exports = {
    http,
    QQMapKey,
    showModal,
    _post,
    _post2,
    showModal1,
    showModal2,
    loginFn,
    dataIndex,
    imgSup,
    upImgAll,
    upImgAllSuccss,
    ewmBtn,
    cwtx1,
    cwtx,
    baseLogin,
    oneImg,
    forC,
    moveFn,
    inputArr,
    rexFn,
    upImgAllSuccssAll,
    inputUn,
    imgUrl,
    payFn,
    passStrat,
    compareVersion,
    canClick,
    ToMiniProgram
}